
from http.client import HTTPException
import logging
from flask import Blueprint

from app.libs.exception import APIException, ParameterException, ServerError, Success
from flask import current_app

bp_api = Blueprint('api', __name__, url_prefix='')

def cite_routes():
    from .v1 import bp_v1
    bp_api.register_blueprint(bp_v1)


cite_routes()
# 全局API错误AOP处理
api_logger = logging.getLogger('api_logger')


@bp_api.errorhandler(Exception)
def framework_error(e: Exception):
    api_logger.error("error info: %s" % e)  # 对错误进行日志记录
    if isinstance(e, APIException):
        return e.response()
    if isinstance(e, HTTPException):
        code = e.code
        msg = e.description
        error_code = 1007
        return APIException(msg, code, error_code).response()

    if isinstance(e, TypeError):
        msg = e.args
        return ParameterException(msg=msg).response()
    else:
        if current_app.config['DEBUG']:
            # code = e.code
            # AttributeError
            # msg = e.description
            #  error_code = 9999
            print(e)
            return ServerError().response()
        else:
            return ServerError().response()
